package com.example.wyh.intelcheckbash;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.common.SysExitUtil;

import org.json.JSONObject;

import java.io.File;

import static android.app.PendingIntent.getActivity;

/**
 * Created by WYH on 17/11/6.
 */

public class AboutActivity extends AppCompatActivity{
    DownloadManager mDownloadManager;
    long downloadId;
    boolean isDownloadComplete = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_activity);
        initActionBar();
        SysExitUtil.activityList.add(AboutActivity.this);
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        TextView main_footer_version_name = (TextView)findViewById(R.id.version_code);
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            int currentVersionCode = info.versionCode; // 版本号
            main_footer_version_name.setText("V "+appVersionName);
//            Log.e("currentVersionCode,appVersionName",currentVersionCode + " " + appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch blockd
            e.printStackTrace();
        }

        Button update_button = (Button)findViewById(R.id.update_app_btn_id);
        update_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isDownloadComplete == true)
                {
                    PackageManager packageManager = getPackageManager();
                    String appVersionName = "1.00.0000";
                    try {
                        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
                        appVersionName = info.versionName; // 版本名
                        int currentVersionCode = info.versionCode; // 版本号

                    } catch (PackageManager.NameNotFoundException e) {
                        // TODO Auto-generated catch blockd
                        e.printStackTrace();
                    }
                    HttpUtil.requestNetForUpdataApp(appVersionName,AboutActivity.this);
                }else
                {
                    showAlert("正在下载新版本...");
                }

            }
        });

    }

    public void showAlert(String msg)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(AboutActivity.this);
        final View layout = layoutInflater.inflate(R.layout.promot_alert,
                null);

        final AlertDialog alertDialog = new AlertDialog.Builder(AboutActivity.this).setTitle("").setView(layout)
                .setPositiveButton("",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView)layout.findViewById(R.id.promot_alert_title);
        alert_title.setText(msg);
        Button confirm = (Button)layout.findViewById(R.id.promot_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    public void downloadAPK(String jsonResult)
    {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonResult);
            String updatePath = jsonObject.getString("path");
            downloadUpdateAPK(updatePath);
        }catch (Exception e)
        {
            Handler mainHander = new Handler(Looper.getMainLooper());
            mainHander.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AboutActivity.this,"没有新版本",Toast.LENGTH_SHORT).show();
                }
            });
        }



    }

    public void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            Log.e("文件存在！","===========");
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        } else {
            Log.e("文件不存在！","===========");
        }
    }
    public void downloadUpdateAPK(String strDownloadUrl)
    {
        isDownloadComplete = false;
        //使用系统下载类
        Uri uri = Uri.parse(strDownloadUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setAllowedOverRoaming(false);

        File file = new File(AboutActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "indexhello.apk");
        deleteFile(file);

        //创建目录下载
        request.setDestinationInExternalFilesDir(AboutActivity.this,Environment.DIRECTORY_DOWNLOADS, "indexhello.apk");
        // 把id保存好，在接收者里面要用
        downloadId = mDownloadManager.enqueue(request);
        //设置允许使用的网络类型，这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //机型适配
        request.setMimeType("application/vnd.android.package-archive");
        //通知栏显示
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("测试APP");
        request.setDescription("正在下载中...");
        request.setVisibleInDownloadsUi(true);

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                checkStatus();
            }
        };
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    installAPK();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(AboutActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        cursor.close();
    }

    private void installAPK() {
        isDownloadComplete = true;
        File apkFile =
                new File(AboutActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "indexhello.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(AboutActivity.this.getApplicationContext(), "com.mydomain.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        AboutActivity.this.startActivity(intent);
    }

    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(AboutActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("关   于");
        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.set_title);
        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 AboutActivity.this.finish();
            }
        });
    }

}
